package com.example.myapplication;

import android.content.Context;
import android.media.projection.MediaProjection;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.google.android.material.button.MaterialButton;

import org.json.JSONObject;


public class HandleWebSocket {

    private final Context context;
    private MediaProjection mediaProjection;
    private WebSocketManager webSocketManager;
    private String deviceId; // 当前设备ID
    private Handler heartbeatHandler;
    private Runnable heartbeatRunnable;
    // 构造函数
    public HandleWebSocket(Context context) {
        this.context = context;
    }

    public void setMediaProjection(MediaProjection mediaProjection) {
        this.mediaProjection = mediaProjection;
    }

    /**
     * 连接设备并注册
     */
    public void connectDevice(String deviceName, MaterialButton button, String JWT_TOKEN, Runnable onCompleted) {
        if (deviceName == null || deviceName.isEmpty()) return;

        int redColor = ContextCompat.getColor(context, R.color.red);
        button.setBackgroundColor(redColor);
        button.setEnabled(false);

        webSocketManager = new WebSocketManager(new WebSocketManager.OnWebSocketListener() {
            @Override
            public void onError(@NonNull String errorMessage) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    Toast.makeText(context, "连接失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    if (onCompleted != null) onCompleted.run();
                });
            }

            @Override
            public void onMessageReceived(@NonNull String message) {
                Log.d("WebSocket", "收到服务器消息: " + message);

                try {
                    JSONObject data = new JSONObject(message);
                    String action = data.optString("action");

                    switch (action) {
                        case "registered":
                            deviceId = data.optString("deviceId");
                            Log.d("WebSocket", "安卓连接成功 deviceId=" + deviceId);
                            Toast.makeText(context, "安卓连接成功 deviceId=" + deviceId, Toast.LENGTH_SHORT).show();
                            startHeartbeat(JWT_TOKEN); // 开启心跳
                            break;

                        case "control":
                            if (deviceId == null) {
                                Log.e("WebSocket", "deviceId 尚未注册，无法执行 control");
                                return;
                            }

                            JSONObject from = data.optJSONObject("from");
                            JSONObject payload = data.optJSONObject("payload");


                            String instruction = payload.optString("Instruction");
                            JSONObject node = new JSONObject();
                            Log.d("指令", instruction);
                            switch (instruction) {
                                case "node":
                                    Log.d("WebSocket", "执行 node 上传");
                                    MyAccessibilityService service = MyAccessibilityService.getInstance();
                                    if (service != null) {
                                        node = service.getAllWindowsUiJson();
                                    }
//                                    Log.d("WebSocket", "当前节点 JSON: " + node);


                                case "Screenshot":
                                    Log.d("WebSocket", "执行 Screenshot 上传");

                                    if (mediaProjection == null) {
                                        Log.e("WebSocket", "MediaProjection 未初始化，无法截图");
                                        return;
                                    }
                                    final JSONObject nodeCopy = node;
                                    MyScreenshot screenshot = new MyScreenshot(context, mediaProjection);
                                    screenshot.captureScreen(new MyScreenshot.Callback() {
                                        @Override
                                        public void onSuccess(String base64) {
                                            Log.d("WebSocket", "截图 Base64 长度: " + base64.length());
                                            try {
                                                JSONObject msgContent = new JSONObject();
                                                msgContent.put("screenshotBase64", base64);
                                                msgContent.put("node", nodeCopy);
                                                String deviceId = payload.optString("deviceId");
                                             String response=  sendWebSocketResponse(
                                                        "control-response",
                                                        JWT_TOKEN,
                                                        deviceId,
                                                        from != null ? from.optString("deviceId") : "",
                                                        msgContent
                                                );
                                                if (webSocketManager != null) {
                                                    webSocketManager.sendMessage(response);
                                                }
                                            } catch (Exception e) {
                                                Log.e("WebSocket", "构建截图消息失败", e);
                                            }
                                        }

                                        @Override
                                        public void onFailed(String error) {
                                            Log.e("WebSocket", "截图失败: " + error);
                                        }
                                    });
                                    break;

                                default:
                                    Log.d("WebSocket", "未知指令消息: " + message);
                                    break;
                            }

                            break;

                        case "rtc-offer":
                            Log.d("WebSocket", "收到 rtc-offer");
                            break;

                        case "rtc-answer":
                            Log.d("WebSocket", "收到 rtc-answer");
                            break;

                        case "ice":
                            Log.d("WebSocket", "收到 ice candidate");
                            break;

                        case "heartbeat-ack":
                            Log.d("WebSocket", "心跳成功");
                            break;
                        case "refreshToken":
                            Log.d("WebSocket", "心跳换token");


                            break;

                        case "android-broadcast":
                            String broadcastMsg = data.optString("msg");
                            Log.d("WebSocket", "广播: " + broadcastMsg);
                            break;

                        default:
                            Log.d("WebSocket", "未知消息: " + message);
                            break;
                    }

                } catch (Exception e) {
                    Log.e("WebSocket", "解析消息失败: " + message, e);
                }
            }
        });

        webSocketManager.connect("ws://192.168.1.104:3000");

        // 延迟发送注册消息
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            try {
                JSONObject payload = new JSONObject();
                payload.put("token", JWT_TOKEN);
                payload.put("deviceName", deviceName);
                payload.put("deviceType", "android");

                JSONObject message = new JSONObject();
                message.put("action", "register");
                message.put("payload", payload);

                webSocketManager.sendMessage(message.toString());
                Toast.makeText(context, "设备已连接：" + deviceName, Toast.LENGTH_SHORT).show();
                if (onCompleted != null) onCompleted.run();
            } catch (Exception e) {
                Log.e("WebSocket", "发送注册消息失败", e);
                if (onCompleted != null) onCompleted.run();
            }
        }, 200);
    }

    /**
     * 断开设备
     */
    public void disconnectDevice(String deviceName, MaterialButton button, Runnable onCompleted) {
        if (webSocketManager != null) {
            webSocketManager.disconnect();
            webSocketManager = null;
        }
        int grayColor = ContextCompat.getColor(context, R.color.primary);
        button.setBackgroundColor(grayColor);
        button.setEnabled(true);
        if (onCompleted != null) onCompleted.run();
        Toast.makeText(context, "设备已断开：" + deviceName, Toast.LENGTH_SHORT).show();
    }

    /**
     * 发送控制指令响应给服务器
     *
     * @param action         WebSocket action 名称，如 "control-response" 或 "screenshot-response"
     * @param JWT_TOKEN      用户的 JWT token
     * @param deviceId       当前设备 ID
     * @param targetDeviceId 目标设备 ID，可为空
     * @param msgJson        JSONObject，将作为 payload 中 msg 的值
     * @return               发送的 JSON 字符串，如果发送失败返回 null
     */
    public String sendWebSocketResponse(String action, String JWT_TOKEN, String deviceId, String targetDeviceId, JSONObject msgJson) {
        try {
            JSONObject payload = new JSONObject();
            payload.put("msg", msgJson != null ? msgJson : new JSONObject());
            payload.put("token", JWT_TOKEN);
            payload.put("from", new JSONObject().put("deviceId", deviceId));
            payload.put("targetDeviceId", targetDeviceId != null ? targetDeviceId : "");

            JSONObject response = new JSONObject();
            response.put("action", action);
            response.put("payload", payload);



            return response.toString();
        } catch (Exception e) {
            Log.e("WebSocket", "拼接 WebSocket 响应失败", e);
            return null;
        }
    }

    private void startHeartbeat(String JWT_TOKEN) {
        stopHeartbeat(); // 防止重复开启

        heartbeatHandler = new Handler(Looper.getMainLooper());
        heartbeatRunnable = new Runnable() {
            @Override
            public void run() {
                if (webSocketManager != null && webSocketManager.isConnected()) { // 确认连接存在
                    try {
                        JSONObject payload = new JSONObject();
                        payload.put("token", JWT_TOKEN);

                        JSONObject heartbeatMsg = new JSONObject();
                        heartbeatMsg.put("action", "heartbeat");
                        heartbeatMsg.put("payload", payload);

                        webSocketManager.sendMessage(heartbeatMsg.toString());
                        Log.d("WebSocket", "心跳发送成功");
                    } catch (Exception e) {
                        Log.e("WebSocket", "心跳发送失败", e);
                    }
                }
                // 30秒后再次执行
                heartbeatHandler.postDelayed(this, 30000);
            }
        };

        // 启动心跳
        heartbeatHandler.postDelayed(heartbeatRunnable, 0);
    }

    private void stopHeartbeat() {
        if (heartbeatHandler != null && heartbeatRunnable != null) {
            heartbeatHandler.removeCallbacks(heartbeatRunnable);
            heartbeatHandler = null;
            heartbeatRunnable = null;
        }
    }

}
